<template>
  <v-container fluid>
    <div v-if="loading" class="text-center pa-10">
      <HamsterLoader />
      <p class="mt-4">正在加载模板编辑器...</p>
    </div>

    <v-form v-else ref="v4Form">

      <v-card class="mb-6">
        <v-card-title class="text-h6 font-weight-bold">
          {{ isEditMode ? '编辑训练模板' : '创建新模板' }}
        </v-card-title>
        <v-card-text>
          <v-row>
            <v-col cols="12">
              <v-text-field
                  v-model="template.name"
                  label="模板名称"
                  placeholder="例如: 办公室拉伸模板"
                  variant="outlined"
                  :rules="[v => !!v || '模板名称不能为空']"
                  required
              ></v-text-field>
            </v-col>
            <v-col cols="12" md="6">
              <v-select
                  v-model="template.goal"
                  :items="goalOptions"
                  label="训练目标"
                  variant="outlined"
                  clearable
              ></v-select>
            </v-col>
            <v-col cols="12" md="6">
              <v-select
                  v-model="template.difficulty"
                  :items="difficultyOptions"
                  label="难度等级"
                  variant="outlined"
                  clearable
              ></v-select>
            </v-col>
            <v-col cols="12" md="6">
              <v-text-field
                  v-model.number="template.estimatedDurationMin"
                  label="预计时长 (分钟)"
                  type="number"
                  placeholder="例如: 30"
                  variant="outlined"
                  clearable
              ></v-text-field>
            </v-col>
            <v-col cols="12" md="6">
              <v-combobox
                  v-model="template.tags"
                  label="标签 (多个标签请按回车)"
                  placeholder="例如: 居家, 无器械"
                  chips
                  multiple
                  closable-chips
                  variant="outlined"
              ></v-combobox>
            </v-col>
            <v-col cols="12">
              <v-textarea
                  v-model="template.description"
                  label="模板描述 (可选)"
                  placeholder="描述这个训练模板的特点, 适合人群等..."
                  variant="outlined"
                  rows="3"
                  auto-grow
              ></v-textarea>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>

      <v-card class="mb-6">
        <v-card-title class="d-flex justify-space-between align-center">
          <span>周计划 (拖拽动作到对应日期)</span>
          <v-btn variant="text" size="small" @click="clearAllItems">清空所有计划</v-btn>
        </v-card-title>
        <v-card-text>
          <v-row class="d-flex flex-nowrap" style="overflow-x: auto; min-height: 200px;">
            <v-col
                v-for="day in weekDays"
                :key="day.value"
                cols="12" md="3" sm="4"
                style="min-width: 250px;"
            >
              <div
                  class="day-drop-zone pa-3 rounded-lg"
                  @dragover.prevent
                  @drop="onDrop(day.value)"
              >
                <div class="text-subtitle-1 font-weight-bold mb-2">{{ day.text }}</div>
                <div v-if="getExercisesForDay(day.value).length === 0" class="text-center text-caption text-medium-emphasis">
                  拖拽动作至此
                </div>
                <v-chip
                    v-for="(item, index) in getExercisesForDay(day.value)"
                    :key="index"
                    class="ma-1"
                    closable
                    color="primary"
                    variant="flat"
                    @click:close="removeItem(day.value, index)"
                >
                  {{ item.exerciseName }}
                </v-chip>
              </div>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>

      <v-card>
        <v-card-title>可拖动动作 (点击或拖拽添加)</v-card-title>
        <v-card-text>
          <v-row>
            <v-col cols="12" md="3">
              <v-text-field v-model="exerciseFilter.nameKeyword" label="搜索动作" density="compact" variant="outlined" hide-details clearable @update:model-value="debouncedFetchExercises"></v-text-field>
            </v-col>
            <v-col cols="12" md="2">
              <v-select v-model="exerciseFilter.exerciseType" :items="exerciseTypeOptions" label="类型" density="compact" variant="outlined" hide-details clearable @update:model-value="fetchExercises"></v-select>
            </v-col>
            <v-col cols="12" md="2">
              <v-select v-model="exerciseFilter.bodyPart" :items="bodyPartOptions" label="部位" density="compact" variant="outlined" hide-details clearable @update:model-value="fetchExercises"></v-select>
            </v-col>
            <v-col cols="12" md="2">
              <v-select v-model="exerciseFilter.libDifficulty" :items="difficultyOptions" label="难度" density="compact" variant="outlined" hide-details clearable @update:model-value="fetchExercises"></v-select>
            </v-col>
            <v-col cols="12" md="3">
              <v-select v-model="exerciseFilter.equipment" :items="equipmentOptions" label="器械" density="compact" variant="outlined" hide-details clearable @update:model-value="fetchExercises"></v-select>
            </v-col>
          </v-row>

          <div class="exercise-grid mt-4">
            <v-row v-if="exercises.length > 0">
              <v-col
                  v-for="exercise in exercises"
                  :key="exercise.id"
                  cols="12" md="6" lg="4"
              >
                <v-sheet
                    border
                    rounded="lg"
                    class="pa-3 exercise-card"
                    draggable="true"
                    @dragstart="onDragStart(exercise)"
                    @click="openAddToDayDialog(exercise)"
                >
                  <div class="d-flex justify-space-between align-center">
                    <div class="font-weight-bold">{{ exercise.name }}</div>
                    <v-icon size="small">mdi-drag-horizontal-variant</v-icon>
                  </div>
                  <div class="text-caption text-medium-emphasis">
                    {{ exercise.bodyPart }} | {{ formatDifficulty(exercise.difficulty) }}
                  </div>
                </v-sheet>
              </v-col>
            </v-row>
            <div v-else class="text-center pa-4 text-caption text-medium-emphasis">
              未找到匹配的运动。
            </div>
          </div>

        </v-card-text>
      </v-card>

      <v-card-actions class="mt-6 pa-0">
        <v-spacer></v-spacer>
        <v-btn variant="text" size="large" @click="router.back()">取消</v-btn>
        <v-btn
            color="primary"
            size="large"
            variant="flat"
            @click="handleSaveTemplate"
            :loading="isSaving"
        >
          {{ isEditMode ? '保存模板' : '创建模板' }}
        </v-btn>
      </v-card-actions>

    </v-form>

    <v-dialog v-model="addToDayDialog.show" max-width="400px">
      <v-card v-if="addToDayDialog.selectedExercise">
        <v-card-title>添加到哪一天?</v-card-title>
        <v-card-text>
          将 **"{{ addToDayDialog.selectedExercise.name }}"** 添加到...
        </v-card-text>
        <v-list>
          <v-list-item
              v-for="day in weekDays"
              :key="day.value"
              :title="day.text"
              @click="addItemToDay(day.value)"
          ></v-list-item>
        </v-list>
      </v-card>
    </v-dialog>

  </v-container>
</template>

<script setup>
// 【!! V4.1 最终修复版 !!】
// (JS/Script 部分在 5:27 PM (JST) 已经 100% 正确了)
// (我们无需修改任何 JS 逻辑)
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Request from '@/utils/Request';
import { debounce } from 'lodash-es';
import { useNotificationStore } from '@/stores/notification';
import HamsterLoader from "@/components/HamsterLoader.vue";

const route = useRoute();
const router = useRouter();
const notificationStore = useNotificationStore();
const v4Form = ref(null);
const loading = ref(true);
const isSaving = ref(false);
const isEditMode = computed(() => !!route.params.id);

const template = reactive({
  id: null,
  name: '',
  goal: null,
  description: '',
  difficulty: null,
  estimatedDurationMin: null,
  tags: [],
  items: [],
});

const weekDays = [
  { text: '周一 (Day 1)', value: 0 }, { text: '周二 (Day 2)', value: 1 },
  { text: '周三 (Day 3)', value: 2 }, { text: '周四 (Day 4)', value: 3 },
  { text: '周五 (Day 5)', value: 4 }, { text: '周六 (Day 6)', value: 5 },
  { text: '周日 (Day 7)', value: 6 },
];
const addToDayDialog = reactive({ show: false, selectedExercise: null });

const exercises = ref([]);
const exerciseFilter = reactive({
  nameKeyword: '',
  libDifficulty: null,
  exerciseType: null,
  bodyPart: null,
  equipment: null,
  pageNumber: 1,
  pageSize: 50
});

const goalOptions = [
  { title: '减脂', value: 0 }, { title: '增肌', value: 1 }, { title: '保持', value: 2 }
];
const difficultyOptions = [
  { title: '零基础适配', value: 3 }, { title: '初级', value: 0 },
  { title: '中级', value: 1 }, { title: '高级', value: 2 }
];
const exerciseTypeOptions = [
  { title: '力量训练', value: 0 }, { title: '有氧训练', value: 1 }, { title: '拉伸放松', value: 2 }
];
const equipmentOptions = [
  { title: '无器械', value: 0 }, { title: '哑铃', value: 1 },
  { title: '弹力带', value: 2 }, { title: '健身房器械', value: 3 }
];
const bodyPartOptions = ['胸部', '背部', '腿部', '肩部', '手臂', '核心', '全身', '臀部'];

const fetchExercises = async () => {
  try {
    const response = await Request.get('/exercises', exerciseFilter);
    exercises.value = response.data;
  } catch (error) { console.error(error); }
};
const debouncedFetchExercises = debounce(fetchExercises, 500);

const fetchTemplateDetail = async () => {
  if (!isEditMode.value) {
    loading.value = false;
    return;
  }
  try {
    const response = await Request.get(`/workout-templates/${route.params.id}`);
    const detail = response.data;
    template.id = detail.id;
    template.name = detail.name;
    template.goal = detail.goal;
    template.description = detail.description;
    template.difficulty = detail.difficulty;
    template.estimatedDurationMin = detail.estimatedDurationMin;
    template.tags = detail.tags ? detail.tags.split(',') : [];
    template.items = detail.items.map(item => ({
      exerciseId: item.exerciseId,
      exerciseName: item.exerciseName,
      dayOffset: item.dayOffset,
      sets: item.sets,
      reps: item.reps,
      intensity: item.intensity?.toString()
    }));
  } catch (error) {
    notificationStore.error('加载模板失败');
    await router.push({ name: 'MyTemplates' });
  } finally {
    loading.value = false;
  }
};

const handleSaveTemplate = async () => {
  const { valid } = await v4Form.value.validate();
  if (!valid) {
    notificationStore.warning('请检查表单, 模板名称不能为空');
    return;
  }
  isSaving.value = true;
  try {
    const payload = {
      name: template.name,
      goal: template.goal,
      description: template.description,
      difficulty: template.difficulty,
      estimatedDurationMin: template.estimatedDurationMin,
      tags: template.tags.join(','),
      items: template.items.map(item => ({
        exerciseId: item.exerciseId,
        dayOffset: item.dayOffset,
        sets: item.sets ?? 3,
        reps: item.reps ?? '10',
        intensity: item.intensity,
      })),
    };
    if (isEditMode.value) {
      await Request.put(`/workout-templates/${template.id}`, payload);
      notificationStore.success('模板更新成功！');
    } else {
      await Request.post('/workout-templates', payload);
      notificationStore.success('新模板创建成功！');
    }
    await router.push({ name: 'MyTemplates' });
  } catch (error) {
    console.error(error);
  } finally {
    isSaving.value = false;
  }
};

const getExercisesForDay = (dayOffset) => {
  return template.items.filter(item => item.dayOffset === dayOffset);
};

let draggedExercise = null;
const onDragStart = (exercise) => {
  draggedExercise = exercise;
};
const onDrop = (dayOffset) => {
  if (draggedExercise) {
    template.items.push({
      exerciseId: draggedExercise.id,
      exerciseName: draggedExercise.name,
      dayOffset: dayOffset,
      sets: 3, reps: '12', intensity: null,
    });
    draggedExercise = null;
  }
};

const openAddToDayDialog = (exercise) => {
  addToDayDialog.selectedExercise = exercise;
  addToDayDialog.show = true;
};
const addItemToDay = (dayOffset) => {
  const exercise = addToDayDialog.selectedExercise;
  if (exercise) {
    template.items.push({
      exerciseId: exercise.id,
      exerciseName: exercise.name,
      dayOffset: dayOffset,
      sets: 3, reps: '12', intensity: null,
    });
  }
  addToDayDialog.show = false;
  addToDayDialog.selectedExercise = null;
};

const removeItem = (dayOffset, index) => {
  const dayItems = getExercisesForDay(dayOffset);
  const itemToRemove = dayItems[index];
  template.items = template.items.filter(item => item !== itemToRemove);
};
const clearAllItems = () => {
  if (confirm('确定要清空所有日期的动作吗？')) {
    template.items = [];
  }
};

const formatDifficulty = (difficulty) => {
  const map = { 0: '初级', 1: '中级', 2: '高级', 3: '零基础' };
  return map[difficulty] ?? '未知';
}

onMounted(() => {
  fetchExercises();
  fetchTemplateDetail();
});
</script>

<style scoped>
.day-drop-zone {
  border: 2px dashed #e0e0e0;
  min-height: 180px;
  height: 100%;
  transition: background-color 0.2s ease;
}
.day-drop-zone:hover {
  background-color: #fafafa;
  border-color: #764ba2;
}
/* (V4.2 新样式) 周计划拖拽区域 */
.day-drop-zone {
  border: 2px dashed #e0e0e0;
  min-height: 180px;
  height: 100%;
  transition: background-color 0.2s ease;
}
.day-drop-zone:hover {
  background-color: #fafafa;
  border-color: #764ba2;
}

.exercise-grid {
  max-height: 50vh;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 8px;
}

/* (新) 运动卡片样式 */
.exercise-card {
  cursor: grab;
  transition: background-color 0.2s ease;
}
.exercise-card:hover {
  background-color: #f5f5f5;
}
.exercise-card:active {
  cursor: grabbing;
}
</style>